<?php

namespace App\model;

use app\common\Page;

class ArticleModel extends ModelBase
{
    protected $name = 'base_article';
    protected $pk = 'article_id';
    protected $pk_name = '内容ID';
    protected $app_id = 0;
    protected $hav_deleted_column=0;
    protected $checkField = [
        ['column'=>'title','name'=>'内容标题'],
    ];

    public function __construct(array $data = [],$app_id=0)
    {
        $this->app_id=$app_id;
        parent::__construct($data);
    }

    public function articleClass()
    {
        return $this->belongsTo('ArticleClassModel', 'article_class_id', 'article_class_id');
    }

    public function checkFieldExistence($field,$val,$pk=0){
        if($this->hav_deleted_column){
            $res = $this->where([[$field,'=',$val],[$this->pk,'<>',$pk],['app_id','=',$this->app_id],['deleted','=',0]])->find();
            return $res?1:0;
        }
        else{
            $res = $this->where([[$field,'=',$val],[$this->pk,'<>',$pk],['app_id','=',$this->app_id]])->find();
            return $res?1:0;
        }

    }

    public function lst($where=[],$order='add_time desc'){
        $where[]=['app_id','=',$this->app_id];
        $count = $this->where($where)->count();
        $page = new Page($count,input('limit',$count),input('page',1));
        $lst = $this::with(['articleClass'])->where($where)->limit($page->firstRow , $page->listRows)->order($order)->select();
//        $lst->hidden(['content']);
        $res['code'] = 0;
        $res['list'] = $lst;
        $res['count'] = $count;
        $res['totalPages'] = $page->totalPages;
        return $res;
    }

    public function add($data=[]){
        $_data = array_merge((json_decode(rawBody(),true) ?? []),$data);
        if(empty($_data)){
            return error(1,'请求数据不能为空');
        }
        foreach($this->checkField as $field){
            if($this->checkFieldExistence($field['column'],$_data[$field['column']])){
                return error(1,$field['name'].'"'.$_data[$field['column']].'"已存在');
            }
        }
        $_data['app_id']=$this->app_id;
        $_data['add_time']=time();
        $res = $this->insertGetId($_data);
        return $res;
    }
}